package com.fnzn.entranceGuard.service;

import com.fnzn.entranceGuard.bean.GuardWhiteList;
import com.fnzn.entranceGuard.entity.*;
import com.fnzn.entranceGuard.mapper.*;
import com.fnzn.entranceGuard.rest.guard.UsrUtil;
import com.fnzn.entranceGuard.util.DateTools;
import com.fnzn.entranceGuard.vo.GuardRole;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.ParseException;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * @author wf_sxf@163.com
 * @date 2018-05-28 10:15
 */
@Service
@Slf4j
public class AuthGuardService {



    @Autowired
    private GuardRoleDeviceMapper roleMapper;
    @Autowired
    private GuardDeviceMapper deviceMapper;
    @Autowired
    private GuardQrInfoMapper qrMapper;
    @Autowired
    private GuardHubCodeMapper codeMapper;
    @Autowired
    private GuardWhiteListMapper whiteMapper;
    @Autowired
    private GuardQrShareMapper shareMapper;
    @Autowired
    private GuardIcInfoMapper guardIcInfoMapper;


    /**
     * 授权开门
     *
     * @param qr 二维码信息
     * @return
     */
    public void checkAuth(QR qr) throws ParseException {
        try {
            GuardQrInfo qrInfo = qrMapper.selectById(qr.getQrId());
            if(StringUtils.isBlank(qr.getUserId())){
                qrInfo.setIsValid(GuardQrInfo.NOTVALIAD);
                qrInfo.setDescription("二维码信息错误，请刷新二维码后重试。");
                qrInfo.setStatus("500");
                qrMapper.updateById(qrInfo);
            }
            if (qrInfo != null) {

                //判断时间戳
                if (DateTools.datePoorDiffSecond(qr.getTime(), DateTools.getCurrentSysData(DateTools.FULL_FORMAT)) > 0) {
                    //不可用
                    qrInfo.setDescription("授权二维码已过期，请重新获取。");
                    qrInfo.setStatus("300");
                    log.info(qrInfo.toString());
                    qrMapper.updateById(qrInfo);
                    return;
                }
                //是否是分享二维码
               /* if(qr.isShare()){
                    openDoorByShare(qr,qrInfo);
                }else{*/
                   if(openDoor(qr,qrInfo)) {
                       return ;
                   }
                //}
            }
            log.info("用户："+qr.getUserId()+",开门失败，无权限"+"设备号："+qr.getDeviceId());
            qrInfo.setIsValid(GuardQrInfo.NOTVALIAD);
            qrInfo.setDescription("开门失败，无此门权限。");
            qrInfo.setStatus("403");
            qrMapper.updateById(qrInfo);
            log.info(qrInfo.toString());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 门禁 ID卡开门
     * @param hex 读头获取的门禁信息
     * @throws ParseException
     */
    public boolean checkAuth(String hex , String deviceId) throws ParseException {
        try {
            //是否是白名单
            if(whiteList(hex,deviceId)){
                return true;
            }else{
            //TODO 判断门禁卡是否有权限
                GuardIcInfo guardIcInfo = new GuardIcInfo();
                guardIcInfo.setIcId(hex);
                guardIcInfo = guardIcInfoMapper.selectOne(guardIcInfo);
                if(guardIcInfo != null) {
                    List<GuardRole> roles = roleMapper.getByUserId(guardIcInfo.getHouseOwnerId());
                    if (roles != null) {
                        GuardDevice device = new GuardDevice();
                        device.setDeviceId(deviceId);
                        device = deviceMapper.selectOne(device);
                        for (GuardRole r : roles) {
                            if (StringUtils.isNotBlank(r.getDeviceIds()) && r.getDeviceIds().contains(device.getId().toString())) {
                                //发送开🔒请求
                                //查询开锁规范
                                //GuardHubCode hubCode = codeMapper.selectById(device.getHubCode());
                                deviceId = device.getDeviceId();
                                //UsrUtil.publishForDevId(hubCode.getOpen(), deviceId);
                                //异步关🔒
                                //closeDoor(deviceId,hubCode.getClose());
                                return true;
                            }
                        }
                    }
                }
            }
            return false;
        }catch (Exception e){
            e.printStackTrace();
            log.error("普通门禁开门："+e);
            return false;
        }
    }

    /**
     * 白名单过滤
     * @param whiteList
     * @param deviceId
     * @return
     * @throws Exception
     */
    public Boolean whiteList(String whiteList , String deviceId) throws Exception {
        GuardDevice device = deviceMapper.selectById(Integer.parseInt(deviceId));
        List<GuardWhiteList> list = whiteMapper.selectByDeviceAndUser(whiteList,deviceId);
        if (list!=null && list.size()>0) {
            //白名单
            //发送开🔒请求
            //查询开锁规范
            //GuardHubCode hubCode = codeMapper.selectById(device.getHubCode());
            //UsrUtil.publishForDevId(hubCode.getOpen(), deviceId);
            //关🔒
            //closeDoor(deviceId,hubCode.getClose());
            return true;
        } else {
            return false;
        }
    }

    public void closeDoor(String deviceId,String hex){
        CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(5000);
                log.info("关门");
                UsrUtil.publishForDevId(hex, deviceId);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return true;
        });
    }
    /**
     * 自主开门
     * @param qr
     * @param qrInfo
     * @throws Exception
     */
    public boolean openDoor(QR qr, GuardQrInfo qrInfo) throws Exception {
        List<GuardRole> roles = roleMapper.getByUserId(qr.getUserId());
        qrInfo.setIsValid(GuardQrInfo.NOTVALIAD);
        qrInfo.setUpdateTime(new Timestamp(System.currentTimeMillis()));
        if (roles != null) {
            GuardDevice device = new GuardDevice();
            device.setDeviceId(qr.getDeviceId());
            device = deviceMapper.selectOne(device);
            for (GuardRole r : roles) {
                if (StringUtils.isNotBlank(r.getDeviceIds()) && r.getDeviceIds().contains(device.getId().toString())) {
                    //授权成功
                    qrInfo.setIsValid(GuardQrInfo.NOTVALIAD);
                    qrInfo.setDescription("授权成功");
                    qrInfo.setStatus("200");
                    qrMapper.updateById(qrInfo);
                    //发送开🔒请求
                    //查询开锁规范
                    log.info(qrInfo.toString());
                    //GuardHubCode hubCode = codeMapper.selectById(device.getHubCode());
                    String deviceId = device.getDeviceId();
                    //UsrUtil.publishForDevId(hubCode.getOpen(), deviceId);
                    //异步关🔒
                    //closeDoor(deviceId,hubCode.getClose());
                    return true;
                }
            }
        }
        return false;
    }
    /**
     * 分享开门
     * @param qr
     * @param qrInfo
     * @throws Exception
     */
    public void openDoorByShare(QR qr, GuardQrInfo qrInfo) throws Exception {
        GuardQrShare share = shareMapper.selectById(qr.getShareId());
        if(share!=null){
            if(qr.getDeviceId().equals(share.getDeviceId())){
                //授权成功
                qrInfo.setIsValid(GuardQrInfo.NOTVALIAD);
                qrInfo.setDescription("授权成功");
                qrInfo.setStatus("200");
                qrMapper.updateById(qrInfo);
                //发送开🔒请求
                //查询开锁规范
                GuardDevice device = new GuardDevice();
                device.setDeviceId(qr.getDeviceId());
                device = deviceMapper.selectOne(device);
                if(device!=null){
                    log.info(qrInfo.toString());
                    //GuardHubCode hubCode = codeMapper.selectById(device.getHubCode());
                    String deviceId = device.getDeviceId();
                    //UsrUtil.publishForDevId(hubCode.getOpen(), deviceId);
                    //异步关🔒
                    //closeDoor(deviceId,hubCode.getClose());
                    return;
                }
            }
        }
    }
    public static boolean f(){
        int[] i ={1,2,3,3};
        for (int e =0;e<3;e++){
            if(e==1){
                return true;
            }
            System.out.println(e);
        }
        return false;
    }

    public static void main(String[] args) {
        //String s = "0x55,0x01,0x11,0x00,0x00,0x00,0x01,0x68";
        System.out.println(f());


    }
}
